package _8_Gorm框架老郭

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
)

func main() {
	// 连接mysql
	dsn := "root:123456@tcp(127.0.0.1:3306)/go_db?charset=utf8mb4&parseTime=True&loc=Local"
	// 创建日志对象
	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			//SlowThreshold: time.Second,   // 慢 SQL 阈值
			LogLevel: logger.Info, // Log level
		},
	)

	db, _ := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger, // 日志配置
	})

	// 案例1：查询西游记的作者信息
	book01 := Bookl{Model: gorm.Model{ID: 10}} // 必须是ID过滤
	// book01 := Bookl{Title: "傲慢与偏见"} // 不可以
	var authors = []Author{}
	db.Model(&book01).Association("Authors").Find(&authors)
	fmt.Println(authors)

	//Association添加 // upsert模式
	a1 := Author{}
	db.Where(Author{Model: gorm.Model{ID: 1}}).Find(&a1)
	db.Model(&Bookl{Model: gorm.Model{ID: 10}}).Association("Authors").Append([]Author{a1, {Name: "Jeorge", Age: 22}})

	//Association删除
	book02 := Bookl{Model: gorm.Model{ID: 10}}
	db.Model(&book02).Association("Authors").Delete(Author{Model: gorm.Model{ID: 1}})
	db.Model(&book02).Association("Authors").Clear()

	//Association替换
	book03 := Bookl{Model: gorm.Model{ID: 10}}
	db.Model(&book03).Association("Authors").Replace([]Author{{Name: "Jeorge", Age: 22}}) // reset
	db.Model(&book03).Association("Authors").Replace(&Author{Model: gorm.Model{ID: 2}})   // reset

	//Association计数
	// 统计傲慢与偏见的作者的个数
	book04 := Bookl{Model: gorm.Model{ID: 10}}
	ret := db.Model(&book04).Association("Authors").Count()
	fmt.Println(ret)
}
